package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrGroupRelationVo;
import com.atguigu.gulimall.product.vo.AttrResVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao relationDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity entity = new AttrEntity();
        BeanUtils.copyProperties(attr, entity);
        //1-保存基本数据
        this.save(entity);
        //2-保存分组关系
        if(attr.getAttrType() == ProductConstant.AttrEnum.AtTTR_BASE_TYPE.getCode() && attr.getAttrGroupId() != null){
            AttrAttrgroupRelationEntity relation = new AttrAttrgroupRelationEntity();
            relation.setAttrGroupId(attr.getAttrGroupId());
            relation.setAttrId(entity.getAttrId());
            relationDao.insert(relation);
        }

    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_type", "base".equals(type) ? 1 : 0);
        if(catelogId != 0){
            wrapper.eq("catelog_id", catelogId);
        }
        String key = (String )params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and((wrapper1)->{
                wrapper1.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrResVo> attrVos = records.stream().map((en) -> {
            AttrResVo resVo = new AttrResVo();
            BeanUtils.copyProperties(en, resVo);
            if ("base".equals(type)){
                AttrAttrgroupRelationEntity rel = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", en.getAttrId()));
                if (null != rel && rel.getAttrGroupId() != null) {
                    Long attrGroupId = rel.getAttrGroupId();
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                    resVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }


            CategoryEntity categoryEntity = categoryDao.selectById(en.getCatelogId());
            if (null != categoryEntity){
                resVo.setCatelogName(categoryEntity.getName());
            }
            return resVo;
        }).collect(Collectors.toList());
        pageUtils.setList(attrVos);
        return pageUtils;
    }

    @Override
    @Cacheable(value = {"attr"}, key = "'attrInfo:' + #root.args[0]")
    public AttrResVo getAttrInfo(Long attrId) {
        AttrEntity attr = this.getById(attrId);
        AttrResVo attrVo = new AttrResVo();
        BeanUtils.copyProperties(attr, attrVo);
        if(attr.getAttrType() == ProductConstant.AttrEnum.AtTTR_BASE_TYPE.getCode()) {
            //设置分组信息
            AttrAttrgroupRelationEntity rel = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (null != rel) {
                attrVo.setAttrGroupId(rel.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(rel.getAttrGroupId());
                attrVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
        }
        //设置分分类
        Long catelogId = attr.getCatelogId();
        Long[] categoryPath = categoryService.findCategoryPath(catelogId);
        attrVo.setCatelogPath(categoryPath);

            CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (null != categoryEntity){
            attrVo.setCatelogName(categoryEntity.getName());
        }
        return attrVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);

        if(attr.getAttrType() == ProductConstant.AttrEnum.AtTTR_BASE_TYPE.getCode()) {
            AttrAttrgroupRelationEntity attrGroupEntity = new AttrAttrgroupRelationEntity();
            attrGroupEntity.setAttrGroupId(attr.getAttrGroupId());
            attrGroupEntity.setAttrId(attr.getAttrId());


            Integer i = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (i > 0) {
                //修改关联分组

                relationDao.update(attrGroupEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            } else {
                relationDao.insert(attrGroupEntity);
            }
        }
    }

    /**根据分组id查询所有基本属性
     * <简述>
     * <详细描述>
     * @author syf
     * @date 2022/3/7 16:11
 * @param attrGroupId
 * @return java.util.List<com.atguigu.gulimall.product.entity.AttrEntity>
     */

    @Override
    public List<AttrEntity> getRelationAttr(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> list = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
        List<Long> ids = list.stream().map((attr) -> {
           return attr.getAttrId();
        }).collect(Collectors.toList());
        Collection<AttrEntity> attrEntities = null;
        if (null != ids && !ids.isEmpty()){
            attrEntities = this.listByIds(ids);
        }

        return   (List<AttrEntity>) attrEntities;
    }


    @Override
    public void deleteRelation(AttrGroupRelationVo[] vo) {
        //relationDao.delete(new QueryWrapper<>().eq("attr_id", ).eq("attr_group_id", ))
        List<AttrGroupRelationVo> attrGroupRelationVos = Arrays.asList(vo);
        List<AttrAttrgroupRelationEntity> collects = attrGroupRelationVos.stream().map((item) -> {
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, entity);
            return entity;
        }).collect(Collectors.toList());

        relationDao.deleteBatchRelations(collects);
    }

    /*
     * <简述>
     * <详细描述>
     * 只能关联未引用
     * @author syf
     * @date 2022/3/7 16:58
     * @param null
     * @return null
     */

    @Override
    public PageUtils getNoRelationAttr(Long attrGroupId, Map<String, Object> params) {
        //当前分组只能关联自己所属分类所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //只能关联别的分组未引用分类
            //1-当前分类其他分组
        List<AttrGroupEntity> groups = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId)
        .ne("attr_group_id", attrGroupId));

        List<Long> collect = groups.stream().map(en -> en.getAttrGroupId()).collect(Collectors.toList());
        //查询这些分组下属性
        List<AttrAttrgroupRelationEntity> attrs = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id",collect));
        List<Long> attrIds = attrs.stream().map(en -> en.getAttrId()).collect(Collectors.toList());
        //移除这些属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type", ProductConstant.AttrEnum.AtTTR_BASE_TYPE.getCode());
        if (null != attrIds && !attrIds.isEmpty()){
            wrapper .notIn("attr_id", attrIds);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                QueryWrapper<AttrEntity> like = w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }

    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
         List<Long> ids  = baseMapper.selectSearchAttrIds(attrIds);
        return ids;
    }


}